<template>
  <view class="data">
    <view class="hd">
      <view @click="show = true">
        <text class="place" v-if="notesLabel == ''">请选择</text>
        <text class="notesLabel" v-else>{{ notesLabel }}</text>
        <u-icon name="arrow-down"></u-icon></view>
      <u-select v-model="show" mode="mutil-column-auto" :list="list" @confirm="fConfirm"></u-select>
    </view>

    <view class="bd">
      <view class="row">
        <u-section title="今日" :right="false" line-color="#2761FF" font-size="33" bold="false"></u-section>
        <view class="content">
          <view class="txt">使用时长</view>
          <view class="time"><text class="blue">{{ hour }}</text>小时 <text class="blue">{{ minute }}</text>分</view>
        </view>
      </view>

      <view class="row">
        <u-section title="历史" :right="false" line-color="#2761FF" font-size="33" bold="false"></u-section>
        <view class="date">
          <text class="btn" v-for="(item,index) in dateList" :key="index" @click="fClickDate(item, index)" :class="{ active: currentIndex === index }">{{ item }}日</text>
        </view>
        <view class="content">
          <uni-ec-canvas v-show="!show" class="uni-ec-canvas" id="uni-ec-canvas" ref="canvas" canvas-id="uni-ec-canvas" :ec="ec">
          </uni-ec-canvas>
        </view>
      </view>
    </view>    
  </view>
</template>

<script>
import { userList, getTodayUserDevUseTime, listTimeUserDevUseTime } from "@/api"
import uniEcCanvas from './components/uni-ec-canvas.vue'
import * as echarts from './components/echarts'
let chart = null

export default {
  data() {
    return {
      list: [],
      show: false,
      notesValue: '',
      notesLabel: '',
      hour: '',
      minute: '',
      ec: {
        lazyLoad: true
      },
      yAxData: null,
      xAxData: null,
      seriesData: null,
      dateList: [7,30],
      currentIndex: 0
    };
  },
  components: {
    uniEcCanvas
  },
  onLoad() {
    // this.$refs.canvas.init(this.initChart);
  },
  async onReachBottom() {
    if(!this.isLoadMore) {
      this.isLoadMore = true
    }
	},
  onPullDownRefresh() {
    uni.showLoading({
      title: '刷新中...',
    })
  },
  onShow() {
    this.fUserList()
    this.fGetTodayUserDevUseTime()
    // this.fClickDate(7, 0)
  },
  methods: {
    getYaxis(value,index){
      const arr = this.yAxData
      if(index < arr.length){
        return arr[index]
      }
    },
    initChart(canvas, width, height, canvasDpr) {
      chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: canvasDpr
      })
      canvas.setChart(chart)
      let _this = this
      let option = {
        tooltip:{
					trigger:"axis",
          axisPointer: {
            type: 'line',  // 鼠标跟随线的类型为直线
            lineStyle: {
              color: '#E6E6E6',  // 鼠标跟随线的颜色
              width: 1,  // 鼠标跟随线的宽度
              type: 'dashed'  // 鼠标跟随线的样式（实线、虚线等）
            }
          },
					backgroundcolor:"rgba(0，22，46，.8)",//设置背景颜色
          boxShadow: "0rpx 0rpx 15rpx 1rpx rgba(0,0,0,0.05)",
          color: "#000",
					textStyle:{
						color: "#fff",
						fontsize: '32rpx',
            padding: '20rpx',
					},
					formatter:(item)=> {
            return `${item[0].name} ${_this.yAxData[item[0].value].replace(':','小时')}分钟`
					},
				},
				grid:{
					top:"6%",
					left:"-6%",
					right:"5%",
					bottom:"0",
					containLabel: true,
				},
				xAxis:[
					{
						type:"category",
						boundaryGap: false,
						axisLine:{
							show: true,
							lineStyle:{
								color: "#AEAEAE",
                // type: "dashed"
              },
            },
						splitArea:{
							show: false,
						},
						axisLabel:{
							textstyle:{
								color:"#fff",
								fontsize: 14,
							},
						},
						axisTick:{
							show: false,
						},
						splitLine:{
							show: false,
						},
						data: this.xAxData,
					},
				],
				yAxis:[
					{
						name:"",
						nameTextstyle: {
							color:"#fff",
						},
						type:"value",
						axisLine:{
							show: false,
              lineStyle:{
								color: "#AEAEAE",
                // type: "dashed"
              },
						},
						axisLabel:{
							textstyle:{
								color:"#fff",
								fontsize:"14",
							},
							formatter:function(value,index){
								return _this.getYaxis(value,index)
							},
						},
						minInterval:1,
						splitLine:{
							show: true,
							lineStyle:{
								// type: "dashed",
								color:"#E6E6E6",
							},
						},
					}
				],
				series :[
					{
						type: "line",
						data: this.seriesData,
						symbolsize:10,
						symbol:"circle",
						smooth: true,
						showSymbol: false,
						lineStyle:{
							width: 3,
							color: "#2761FF", // 线的颜色蓝色
						},
						itemStyle:{
							normal:{
								color:"#2761FF",
							  lineStyle:{
								  color:"#2761FF",
								},
							},
						},
					}
				],
      }
      chart.setOption(option)
      return chart
    },
    fUserList(){
      userList().then(res => {
        this.list = []
        res.data.map(item => {
          this.list.push({
            value: item.userId,
            label: item.notes
          })
        })
      })
    },
    fConfirm(val){
      if(val){
        console.log('val', val)
        this.notesValue = val[0].value
        this.notesLabel = val[0].label

        this.fClickDate(7, 0)
      }
    },
    fGetTodayUserDevUseTime(){
      getTodayUserDevUseTime({ userId: 1 }).then(res => {
        if(res.code === 0){
          let formatTodayUseTime = res.data.formatTodayUseTime
          this.hour = formatTodayUseTime.split('小时')[0]
          this.minute = formatTodayUseTime.split('小时')[1].split('分钟')[0]
        }
      })
    },
    // 将时间字符串转换为分钟数进行比较
    converData(timeStr) {
        const parts = timeStr.split(':').map(Number);
        return parts[0] * 60 + parts[1];
    },
    // 对时间数组去重并排序
    sortTime(times) {
        const uniqueTimes = [...new Set(times)]; // 去重
        uniqueTimes.sort((a, b) => this.converData(a) - this.converData(b)); // 排序
        return uniqueTimes;
    },
    fListTimeUserDevUseTime(startDate, endDate){
      let data = {
        userId: this.notesValue,
        startDate,
        endDate
      }
      listTimeUserDevUseTime(data).then(res => {
        if(res.code === 0){
          let timeArr =[];
          let xAxi =[];
          let seri =[];
          let xAxSeri =[];// series -- 数据渲染
          
          let dataSeri = []
          res.data.map(item => {
            dataSeri.push({
              xAdate: item.day.slice(5).replace('-','.'),
              data: item.formatUseTime.replace('小时',':').replace('分钟','')
            })
          })

          dataSeri.forEach((item)=>{
            timeArr.push(item.data); // 时间片段
            xAxi.push(item.xAdate); // 日期
          });

          seri = this.sortTime(timeArr);
          if(seri.includes("00:00")){
            for(let i=0;i< seri.length; i++){
              for(let j=0;j< dataSeri.length; j++){
                // xxx  -- 时间片段
                if(dataSeri[j].data == seri[i]){
                  // a 后端定义好一个属性存放索引
                  dataSeri[j].a = i+1;
                }
              }
            }
          }else {
            for(let i=0;i< seri.length; i++){
              for(let j=0;j< dataSeri.length; j++){
                // xxx  -- 时间片段
                if(dataSeri[j].data == seri[i]){
                  // a 后端定义好一个属性存放索引
                  dataSeri[j].a = i+1;
                }
              }
            }
          }
          dataSeri.forEach((item) =>{
            xAxSeri.push(item.a);
          });
          
          this.$nextTick(()=>{
            this.yAxData = seri.includes("00:00")? seri:["00:00", ...seri];
            this.xAxData = xAxi;
            this.seriesData = xAxSeri;
            // this.initChart()
            this.$refs.canvas.init(this.initChart);
          });
        }
      })
    },
    fClickDate(day, index){
      this.currentIndex = index
      let date1 = new Date();
      let date2 = new Date(date1);
      date2.setDate(date1.getDate() - day);

      let m = date1.getMonth() + 1;
      m = m < 10 ? ('0' + m) : m
      let d = date1.getDate();    
      d = d < 10 ? ('0' + d) : d;  

      let m2 = date2.getMonth() + 1;
      m2 = m2 < 10 ? ('0' + m2) : m2
      let d2 = date2.getDate();    
      d2 = d2 < 10 ? ('0' + d2) : d2;  

      let startDate = `${date1.getFullYear()}-${m}-${d}`
      let endDate = `${date2.getFullYear()}-${m2}-${d2}`
      this.fListTimeUserDevUseTime(startDate, endDate)
    }
  }
};
</script>

<style scoped lang="scss">
.hd{
  height: 98rpx;
  line-height: 98rpx;
  background: #fff;
  text-align: center;

  .place{
    color: #707070;
  }
  .notesLabel{
    color: #000;
  }
  .place, .notesLabel{
    padding-right: 8rpx;
  }
}

.bd{
  padding: 25rpx;
  background: #F7F7F7;

  .row{
    background: #fff;
    position: relative;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    padding: 24rpx 20rpx;

    .date{
      position: absolute;
      top: 20rpx;
      right: 20rpx;

      .btn{
        width: 90rpx;
        height: 44rpx;
        color: #000;
        line-height: 44rpx;
        background: #EEE;
        border-radius: 35rpx;
        display: inline-block;
        text-align: center;
        font-size: 24rpx;
        margin-left: 14rpx;
      }
      .active{
        color: #2761FF;
        background: #EAEFFC;
      }
    }

    .content{
      text-align: center;
      padding-bottom: 20rpx;

      .txt{
        color: #000;
        font-size: 26rpx;
        padding: 44rpx 0 18rpx 0;
      }
      .blue{
        font-size: 88rpx;
      }
      .time{
        font-size: 24rpx;
      }
    }
  }
}

.uni-ec-canvas {
  width: 100%;
  height: 500rpx;
  display: block;
  margin-top: 30rpx;
  position: relative;
  z-index: 1;
}
</style>